package com.song.mall.member.interceptor;

import com.song.common.constant.AuthServerConstant;
import com.song.common.to.MemberTO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/10/10 - the current system date.
 * 10:03 - the current system time.
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {


    public static ThreadLocal<MemberTO> loginUser  = new ThreadLocal<>() ;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String uri = request.getRequestURI();
        boolean match = new AntPathMatcher().match("/member/**", uri);
        if (match){
            return true;
        }

        MemberTO  attribute = (MemberTO) request.getSession().getAttribute(AuthServerConstant.SESSION_ATTR_NAME);
        if (attribute!=null){
            loginUser.set(attribute);
            return true;
        }else{
            //没登录提示登录 去登录
            request.getSession().setAttribute("msg","请去登录");
            response.sendRedirect("http://auth.mall.com/login.html");
            return false;
        }
    }
}
